﻿using System;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using CML.Intercamber.Business;
using CML.Intercamber.Business.Dao;
using CML.Intercamber.Business.Helper;
using CML.Intercamber.Web.Helpers;

namespace CML.Intercamber.Web.Controllers
{
    //[Authorize]
    //[InitializeSimpleMembership]
    public class AccountController : BaseController
    {
        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            if (ConnectedUserHelper.ConnectedUser != null)
            {
                if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
                    return Redirect(returnUrl);
                return RedirectToAction("Index", "Home");
            }
            ViewBag.HideLeftBar = true;
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        //[ValidateAntiForgeryToken]
        public ActionResult Login(ViewModels.LoginModel model, string returnUrl)
        {
            model.Email = (model.Email ?? "").ToLower();


            ViewBag.HideLeftBar = true;
            Users connectedUser = UsersDao.Login(model.Email, model.Password);

            if (connectedUser != null)
            {
                if (connectedUser.Enabled == false)
                {
                    ViewBag.ErrorMessage = Resources.Intercamber.Login_AccountBlocked + "<br/>" +
                                           connectedUser.BlockMessage + "<br/><br/>"
                                           + Resources.Intercamber.Login_AccountBlockedContact;
                }
                else
                {
                    // connection ok
                    FormsAuthentication.SetAuthCookie(model.Email, false);
                    ConnectedUserHelper.CreateSession(connectedUser);
                    UserConnectionsDao.InsertConnectionLog(connectedUser.IdUser);

                    //success redirect 
                    if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
                        return Redirect(returnUrl);

                    if (connectedUser.MainInformationMissing)
                        return RedirectToAction("MyProfile", "Profile");

                    return RedirectToAction("Index", "Home");    
                }
                
            }
            else
            {
                // connection failed
                ViewBag.ErrorMessage = Resources.Intercamber.Login_BadLoginOrPassword;    
            }
            return Login(null);
        }

        [HttpPost]
        public ActionResult LogOff()
        {
            Session.Abandon();
            FormsAuthentication.SignOut();
            return RedirectToAction("Login", "Account");
        }

        public void ChangeLanguage(string id)
        {
            var cuka = new HttpCookie("_culture") {Expires = DateTime.Now.AddYears(10), Value=id};
            System.Web.HttpContext.Current.Response.Cookies.Add(cuka);
            Response.Redirect(Request.UrlReferrer != null ? Request.UrlReferrer.AbsoluteUri : "/");
        }

        [AllowAnonymous]
        public ActionResult Create(Guid id, Users user)
        {
            ViewBag.ErrorMessage = "";
            ViewBag.FirstName = user != null ? user.FirstName : "";

            // check invitation id 
            var invite = UserInvitesDao.FindInvites(id);

            var textUserExist = invite == null ? null : UsersDao.FindUserByEmail(invite.Email);
            if (textUserExist != null)
            {
                ViewBag.Email = invite.Email;
                return RedirectToAction("Login");
            }

            if (invite == null || invite.AccountCreated)
            {
                if (invite != null)
                    ViewBag.Email = invite.Email;

                ViewBag.ErrorMessage = Resources.Intercamber.Error_InvalidInvite;
                return RedirectToAction("Login");
            }

            // check 
            if (user != null && user.FirstName != null && user.LastName != null)
            {
                bool success = UsersDao.CreateStudentAccount(id, user);
                if (success)
                {
                    FormsAuthentication.SetAuthCookie(user.Email, false);
                    ConnectedUserHelper.CreateSession(user);
                    return RedirectToAction("Index", "Home");
                }
            }
            return View(user);
        }

        #region forgotten passsword
        [AllowAnonymous]
        public ActionResult ForgottenPassword()
        {
            return View();
        }

        [AllowAnonymous]
        public ActionResult ResetPassword(Guid id)
        {
            var info = ForgottenPasswordsDao.Find(id);
            if(info == null)
                return RedirectToAction("Login", "Account");
            ViewBag.Id = id;
            return View();
        }

        [AllowAnonymous]
        public ActionResult ResetPasswordAction(Guid id, string email, string pwd)
        {
            var info = ForgottenPasswordsDao.Find(id);
            if (info == null)
                return Json(new { msg = "Error", ok = false }, JsonRequestBehavior.AllowGet);
            bool ok = ForgottenPasswordsDao.UseKeyAndChangePassword(id, email, pwd);
            if(!ok)
                return Json(new { msg = Resources.Intercamber.Error_ForgottenPasswordChange, ok = false }, JsonRequestBehavior.AllowGet);
            return Json(new { msg = Resources.Intercamber.PasswordChangedConnect, ok = true }, JsonRequestBehavior.AllowGet);
        }


        [AllowAnonymous]
        public JsonResult SendForgottenPasswordLink(string email)
        {
            Thread.Sleep(1000); // security issues

            bool exists = UsersDao.ExistsUserWithEmail(email);
            if(!exists)
                return Json(new { msg = Resources.Intercamber.Error_UnknownEmail, ok = false }, JsonRequestBehavior.AllowGet);
            ForgottenPasswords val = ForgottenPasswordsDao.Add(email);
            if(val == null)
                return Json(new { msg = Resources.Intercamber.Error_UnknownEmail, ok = false }, JsonRequestBehavior.AllowGet);

            // send mail
            string mailSubject = Resources.Intercamber.ForgottenPassword_MailSubject;
            string mailBody = string.Format(Resources.Intercamber.ForgottenPassword_MailBody, 
                new object[]
                {
                    Request.Url.ToString().Replace("Account/SendForgottenPasswordLink", "") + "Account/ResetPassword/" + val.RequestKey, 
                    Request.Url.ToString().Replace("Account/SendForgottenPasswordLink", "") + "Account/Login?returnUrl=/Home/Contact", 
                });
            bool sent = MailHelper.SendMail(email, mailSubject, mailBody);
            if (!sent)
                return Json(new { msg = Resources.Intercamber.Error_CannotSendMail, ok = false }, JsonRequestBehavior.AllowGet);

            return Json(new { msg=Resources.Intercamber.EmailSent, ok=true}, JsonRequestBehavior.AllowGet);
        }
        #endregion 

        #region moderation

        [AllowAnonymous]
        public ActionResult ModerationPopup(long user, string level, string node)
        {
            var connectedUser = ConnectedUserHelper.ConnectedUser;
            if (connectedUser == null)
                return null;
            var userInfo = UsersDao.FindUserById(user);
            ViewBag.User = userInfo;
            ViewBag.Level = level;
            ViewBag.Node = node;
            return View();
        }

        [HttpPost]
        public JsonResult AddModeration(Moderation m)
        {
            var connectedUser = ConnectedUserHelper.ConnectedUser;
            if (connectedUser == null)
                return null;

            var user = ConnectedUserHelper.ConnectedUser;
            m.IdModeration = -1;
            ModerationDao.AddUpdateModeration(m, user);
            return Json(true);
        }

        #endregion 
    }
}
